<template>
  <!-- 信息维护 -- 特行证书 -->
  <view class="staffNewEditor">
    <view class="content">
      <view class="content-item">
        <block v-if="dataFlag != ''">
          <u-form :model="form" ref="form" label-width="100" :error-type="errorType">
            <u-form-item label="证件图片" label-width="70">
              <text style="color: #a1a1a1; font-size: 26rpx">
                (大小2M以内)
              </text>
            </u-form-item>
            <block v-if="dataFlag != 3">
              <u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deletePic(2)" name="file" :maxCount="1"
                width="310" height="215" :delIconCenter="true" :delIconSize="40">
                <image :src="baseImgUrl + 'card_2.png'" style="width: 640rpx; height: 430rpx"></image>
              </u-upload>
            </block>
            <block v-else>
              <image :src="imgPrefix + form.certificateUrl" style="width: 640rpx; height: 430rpx; margin-bottom: 8rpx"
                mode="aspectFill"></image>
            </block>
            <u-form-item label="证书编码" label-width="70">
              <view class="special-class">
                <view>
                  <u--input v-model.trim="form.ccieFirst" :readonly="dataFlag == 3 ? true : false" border="bottom"
                    :maxlength="2"></u--input>
                  <span>公特</span>
                </view>
                <view>
                  <u--input v-model.trim="form.ccieSecond" :readonly="dataFlag == 3 ? true : false" border="bottom"
                    :maxlength="2"></u--input>
                  <span>字第</span>
                </view>
                <view>
                  <u--input v-model.trim="form.ccieThird" :readonly="dataFlag == 3 ? true : false" border="bottom"
                    :maxlength="8"></u--input>
                  <span>号</span>
                </view>
              </view>
            </u-form-item>
            <u-form-item label="发证机关" borderBottom label-width="70">
              <u--input v-model.trim="form.certificateOffice" :readonly="dataFlag == 3 ? true : false" border="none"
                placeholder="请填写" :maxlength="18"></u--input>
            </u-form-item>

            <u-form-item label="发证日期" borderBottom label-width="70" @click="cellTimeClick('certificateDate')">
              <u--input v-model="form.certificateDateName" disabled disabledColor="#ffffff" placeholder="请选择"
                border="none"></u--input>
              <image :src="baseImgUrl + 'day-icon.png'" mode="" slot="right" class="seleTime"></image>
            </u-form-item>
          </u-form>
        </block>
        <block v-else>
          <u-empty mode="list" text="您还没有上传特行证信息" :icon="baseImgUrl + 'no-icon4.png'">
          </u-empty>
        </block>
      </view>
    </view>

    <view class="btns">
      <block v-if="dataFlag == 1 || dataFlag == 2">
        <button class="reset-btn lt cancelBtn" type="primary" @click="cancelHandle">
          取消
        </button>
        <button class="submit-btn" type="primary" @click="submitHandle">
          保存
        </button>
      </block>
      <button v-if="dataFlag == 3" class="lookbtn" type="primary" @click="dataFlag = 2" style="width: 100%">
        修改
      </button>
      <button v-if="dataFlag == ''" class="submit-btn" type="primary" @click="dataFlag = 1" style="width: 100%">
        添加特行证信息
      </button>
    </view>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date" :formatter="formatter"
      :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose" @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
  </view>
</template>

<script>
  import {
    certificateDetail,
    updateCompany,
    smartStructuralOrc,
  } from "@/api/myself.js";
  import {
    Toast,
    navBack,
    formatters,
    dayTurnTime,
    getBase64Two,
    uniTrim,
    isLoading,
    useNetWork,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";
  import {
    timeout
  } from "@/config.js";

  import mixin from "@/utils/mixin.js";

  export default {
    name: "staffNewEditor",
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        form: {},
        errorType: ["none"],
        fileList2: [],
        dataFlag: "", // 1:添加  2编辑  3修改
      };
    },
    onLoad(options) {
      this.options = options;

      certificateDetail({
        companyId: options.companyMessageId
      }).then((res) => {
        let {
          code,
          result
        } = res;
        if (code == 200) {
          if (result.certificateTime) {
            this.dataFlag = 3;
            this.form = {
              ...this.form,
              ...result
            };
            this.form.ccieFirst = result.certificateCodeList[0];
            this.form.ccieSecond = result.certificateCodeList[1];
            this.form.ccieThird = result.certificateCodeList[2];
            if (result.certificateTime) {
              this.form.certificateDateName = formatters(
                result.certificateTime,
                "YY/MM/DD"
              );
              this.form.certificateDate = dayTurnTime(
                this.form.certificateDateName
              );
            }

            if (this.form.certificateUrl) {
              this.fileList2.push({
                url: this.imgPrefix + this.form.certificateUrl,
              });
            }
          } else {
            this.dataFlag = "";
          }
        }
      });
    },
    methods: {
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        if (this.dataFlag == 3) return false;
        this.cellType = e;
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "certificateDate":
            this.maxDate = minDateNum;
            this.timeValue = this.maxDate;
            break;
          default:
            break;
        }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "certificateDate":
              this.form.certificateDate = "";
              this.form.certificateDateName = "";
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "certificateDate":
              this.form.certificateDateName = formatters(arr, "YY/MM/DD");
              this.form.certificateDate = dayTurnTime(
                this.form.certificateDateName
              );
              break;

            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      afterRead2(info) {
        let _this = this;
        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            smartStructuralOrc({
              imageBase64: res
            }).then((res) => {
              // if (res.code != 200) return Toast("请上传正确的特种行业许可证");
              if (res.code != 200) {
                Toast("未识别");
                _this.ocrPicHandle(null, info.file.url);
                return;
              }

              var ocrList = res.result.structuralItems;
              var indexName = ocrList.map((v) => v.name).indexOf("标题");
              var indexvalue = ocrList
                .map((v) => v.value)
                .indexOf("特种行业许可证");

              if (indexName != -1 && indexvalue != -1) {
                _this.ocrPicHandle(ocrList, info.file.url);
                return;
              }

              Toast("未识别");
              _this.ocrPicHandle(null, info.file.url);
            });
          });
      },
      ocrPicHandle(ocrList, urlimg) {
        if (ocrList) {
          ocrList.map((v) => {
            if (v.name == "证字号") {
              let nameV = v.value;
              let gt = nameV.lastIndexOf("公特");
              let zd = nameV.lastIndexOf("字第");
              let num = nameV.lastIndexOf("号");

              let firsta = nameV.slice(0, nameV);
              let firsts = nameV.slice(gt + 2, zd);
              let firstt = nameV.slice(zd + 2, num);
              this.$set(this.form, "ccieFirst", firsta || "");
              this.$set(this.form, "ccieSecond", firsts || "");
              this.$set(this.form, "ccieThird", firstt);
            }

            if (v.name == "日期") {
              let year = v.value.lastIndexOf("年");
              let month = v.value.lastIndexOf("月");
              let day = v.value.lastIndexOf("日");

              var da1 = v.value.slice(0, year); //年
              var da2 = v.value.slice(year + 1, month); // 月
              var da3 = v.value.slice(month + 1, day); // 日
              let gTime = dayTurnTime(`${da1}/${da2}/${da3}`);
              this.form.certificateDateName = formatters(gTime, "YY/MM/DD");
              this.form.certificateDate = gTime;
            }
          });
        }

        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: urlimg,
            timeout: timeout,
            name: "file",
            formData: {
              type: 17,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList2.push({
              url: fullPath
            });
            _this.form.certificateUrl = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic() {
        this.fileList2 = [];
        this.form.certificateUrl = "";
      },
      cancelHandle() {
        if (this.dataFlag == 1) {
          navBack();
        } else if (this.dataFlag == 2) {
          this.dataFlag = 3;
        }
      },
      submitHandle() {
        let {
          certificateUrl,
          ccieFirst,
          ccieSecond,
          ccieThird,
          certificateOffice,
          certificateDate,
        } = this.form;

        if (certificateUrl || ccieThird || certificateOffice || certificateDate) {
          if (!certificateUrl) {
            Toast("请上特殊行业许可证照片");
            return;
          }

          if (!ccieThird || !uniTrim(ccieThird)) {
            Toast("请输入证书编码");
            return;
          }

          if (!certificateOffice || !uniTrim(certificateOffice)) {
            Toast("请输入发证机关");
            return;
          }

          if (!certificateDate) {
            Toast("请选择发证日期");
            return;
          }
        }

        let data = {
          companyQualificationsInfo: {
            id: this.options.companyMessageId,
            certificateCodeList: ccieThird ? [ccieFirst || "", ccieSecond || "", ccieThird] : [],
            certificateUrl: certificateUrl,
            certificateOffice: certificateOffice,
            certificateDate: certificateDate,
          },
        };

        updateCompany(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            navBack();
            return;
          }
          Toast(res.message);
        });
      },
    },
  };
</script>

<style lang="scss">
  .staffNewEditor {
    flex: 1;
    background-color: #f9f9f9;

    .content {
      margin: 0 auto;
      margin-top: 20rpx;
      margin-bottom: 20rpx;
      padding: 0 30rpx;
      border-radius: 8rpx;
      height: calc(100vh - 92px);
      overflow-y: auto;
      background: #fff;

      .content-item {
        padding: 25rpx;

        .special-class {
          display: flex;

          view {
            width: 160rpx;
            display: flex;

            /deep/.u-input {
              width: 60% !important;
            }
          }

          view:nth-of-type(3) {
            width: 180rpx;
          }

          /deep/input {
            padding-right: 0;
          }

          span {
            padding-top: 18rpx;
            font-size: 30rpx;
          }
        }

        .seleTime {
          width: 45rpx;
          height: 45rpx;
        }
      }
    }

    .u-input__content {
      width: 450rpx;
    }

    .btns {
      button {
        border-radius: 44rpx;
      }
    }
  }
</style>